package com.joesem.sale.client.logic.workOrder

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Html
import android.text.Spanned
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener
import com.jiaxing.sale.client.R
import com.jiaxing.sale.client.databinding.ActivityCreateContactBinding
import com.jiaxing.sale.client.databinding.LayoutToolbarBinding
import com.joesem.sale.client.base.*
import com.joesem.sale.client.logic.workOrder.option.optionArea
import com.joesem.sale.client.network.data.ContactMode
import com.joesem.sale.client.utils.activityResult.launcherResult
import com.joesem.sale.client.utils.click
import com.joesem.sale.client.widget.dialog.optionDatePickerSingle

class CreateContactActivity : BaseActivity<ActivityCreateContactBinding>() {

    private val viewModel by createViewModel<CreateContactViewModel>()

    private val values = hashMapOf<String, Any?>().apply {
        this["gender"] = "男"
        this["is_default"] = 1
    }

    override fun LayoutToolbarBinding.toolbar(savedInstanceState: Bundle?) {
        visible()
        toolbarTheme()
        toolbarTitle.text = "添加联系人"
    }

    override fun ActivityCreateContactBinding.initView(savedInstanceState: Bundle?) {
        values["customer_id"] = intent.getIntExtra("customerId", -1)
        intent.getIntExtra("eventId", -1).let {
            if (it > 0) {
                values["event_id"] = it
            }
        }
        tvCustomerName.text = intent.getStringExtra("customerName").orEmpty()
        tvNameTitle.text = getRequiredTitle("联系人姓名")
        tvPhoneTitle.text = getRequiredTitle("联系人电话")
        tvAddressTitle.text = getRequiredTitle("省市区")
        tvAddressDetailsTitle.text = getRequiredTitle("详细地址")
        swDefault.isChecked = true
        rbSex.check(R.id.rbMen)
    }

    @SuppressLint("SetTextI18n")
    override fun ActivityCreateContactBinding.initListener() {
        etName.addTextChangedListener {
            values["name"] = it?.toString()
        }
        etPhone.addTextChangedListener {
            values["phone"] = it?.toString()
        }
        rbSex.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rbMen -> values["gender"] = rbMen.text.toString()
                R.id.rbFemale -> values["gender"] = rbFemale.text.toString()
            }
        }
        etOfficePhone.addTextChangedListener {
            values["office_phone"] = it?.toString()
        }
        etEmail.addTextChangedListener {
            values["email"] = it?.toString()
        }
        btnBirthday.click {
            optionDatePickerSingle(this@CreateContactActivity) {
                values["birthday"] = it
                tvBirthday.text = it
            }
        }
        etRole.addTextChangedListener {
            values["project_role"] = it?.toString()
        }
        btnAddress.click {
            optionArea(supportFragmentManager) { province, city, county ->
                tvAddress.text =
                    province?.name.orEmpty() + city?.name.orEmpty() + county?.name.orEmpty()
                values["county_id"] = county?.id
                values["county_name"] = county?.name
                values["city_id"] = city?.id
                values["city_name"] = city?.name
                values["province_id"] = province?.id
                values["province_name"] = province?.name
            }
        }
        etAddressDetails.addTextChangedListener {
            values["address"] = it?.toString()
        }
        etPosition.addTextChangedListener {
            values["duty"] = it?.toString()
        }
        swDefault.setOnCheckedChangeListener { _, isChecked ->
            values["is_default"] = if (isChecked) 1 else 0
        }
        btnConfirm.click {
            Log.i("打印", "提交: $values")
            viewModel.createContact(values)
        }
    }

    override fun ActivityCreateContactBinding.initIntent(intent: Any?) {
        when (intent) {
            is CreateContactViewModel.ContactIntent -> {
                setResult(Activity.RESULT_OK, Intent().apply {
                    putExtra("createContact", intent.date)
                })
                finish()
            }
        }
    }

    private fun getRequiredTitle(title: String): Spanned {
        return Html.fromHtml(
            """
            <font color='${Color.RED}'>*</font>
            <font color='${R.color.black.color()}'>${title}</font>
        """.trimIndent()
        )
    }
}

class CreateContactViewModel(application: Application) : BaseViewModel(application) {

    fun createContact(values: HashMap<String, Any?>) {
        if (checkValues(values)) {
            request(isLoading = true, request = {
                createContact(values)
            }, response = { it ->
                it.data?.let {
                    actionIntent(ContactIntent(it))
                }
            }, responseFailed = {
                toast(it.message)
            })
        }
    }

    private fun checkValues(values: HashMap<String, Any?>): Boolean {
        if (values["name"] == null || values["name"]?.toString().isNullOrEmpty()) {
            toast("请输入联系人姓名")
            return false
        }
        if (values["phone"] == null || values["phone"]?.toString().isNullOrEmpty()) {
            toast("请输入联系人电话")
            return false
        }
        if (values["province_id"] == null || values["city_id"] == null || values["county_id"] == null) {
            toast("请选择省市区")
            return false
        }
        if (values["address"] == null || values["address"]?.toString().isNullOrEmpty()) {
            toast("请输入详细地址")
            return false
        }
        return true
    }

    class ContactIntent(val date: ContactMode)
}

fun optionCreateContact(
    activity: AppCompatActivity,
    customerId: Int,
    customerName: String,
    eventId: Int? = null,
    result: (ContactMode) -> Unit
) {
    activity.launcherResult<CreateContactActivity>(
        "customerId" to customerId,
        "customerName" to customerName,
        "eventId" to eventId
    ) { _: Int, data: Intent? ->
        data?.let {
            it.getParcelableExtra<ContactMode>("createContact")?.let(result)
        }
    }
}